/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ibmmodel3;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mwh
 */
public class FertilityTableGrep implements FertilityTable {

    String filename;


    public FertilityTableGrep(String filename) {
        this.filename = filename;
    }


    public List<Double> get(int word) {
        try {
            String line = Grep.grepFirst("^" + word + " ", filename);
            String[] tokens = line.split(" ");
            List<Double> ferts = new ArrayList<Double>(tokens.length);
            for (int i=1; i<tokens.length; i++) {
                String t = tokens[i];
                ferts.add(Double.parseDouble(t));
            }
         
            return ferts;

        } catch (FileNotFoundException ex) {
            Logger.getLogger(VocabularyTableGrep.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(VocabularyTableGrep.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new ArrayList<Double>();
    }


    public double get(int word, int fert) {

        List<Double> ferts = get(word);

        if (ferts.size() > fert) {
            return ferts.get(fert);
        }
        return Double.NaN;

    }



//    public double get(int word, int fert) {
//
//        double res = Double.NaN;
//
//        try {
//            String line = Grep.grepFirst("^" + word + " ", filename);
//            String[] tokens = line.split(" ");
//            if (fert + 1 < tokens.length) {
//                res = Double.parseDouble(tokens[fert + 1]);
//            }
//
//        } catch (FileNotFoundException ex) {
//            Logger.getLogger(VocabularyTableGrep.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(VocabularyTableGrep.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        return res;
//    }
    public double getLog10(int word, int fert) {
        return Math.log10(get(word, fert));
    }
}
